"""
边缘优化缩略图面板模块
"""

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import numpy as np
from typing import Dict, Callable

from ...utils import get_logger


class EdgeThumbnailPanel:
    """边缘优化缩略图面板类"""
    
    def __init__(
        self,
        parent: tk.Widget,
        methods: Dict,
        method_order: list,
        on_click_callback: Callable
    ):
        """
        初始化缩略图面板
        
        Args:
            parent: 父容器
            methods: 方法配置字典
            method_order: 方法显示顺序
            on_click_callback: 点击回调函数
        """
        self.parent = parent
        self.methods = methods
        self.method_order = method_order
        self.on_click = on_click_callback
        self.logger = get_logger(__name__)
        
        self.thumbnail_buttons = {}
        self.selected_method = None
        
        # 创建面板
        self._create_panel()
    
    def _create_panel(self):
        """创建缩略图面板"""
        # 创建画布和滚动条
        canvas_frame = tk.Frame(self.parent, height=220)
        canvas_frame.pack(fill=tk.X)
        
        # 横向滚动条
        h_scrollbar = ttk.Scrollbar(canvas_frame, orient=tk.HORIZONTAL)
        h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 画布
        self.thumbnail_canvas = tk.Canvas(
            canvas_frame,
            height=200,
            bg="#f0f0f0",
            highlightthickness=0,
            xscrollcommand=h_scrollbar.set
        )
        self.thumbnail_canvas.pack(side=tk.TOP, fill=tk.X)
        h_scrollbar.config(command=self.thumbnail_canvas.xview)
        
        # 内部框架
        self.thumbnail_inner_frame = ttk.Frame(self.thumbnail_canvas)
        self.thumbnail_canvas.create_window(0, 0, anchor=tk.NW, window=self.thumbnail_inner_frame)
        
        # 创建所有缩略图按钮
        for method_key in self.method_order:
            btn_frame = self._create_thumbnail_button(
                self.thumbnail_inner_frame,
                method_key,
                self.methods[method_key]
            )
            btn_frame.pack(side=tk.LEFT, padx=5, pady=5)
            self.thumbnail_buttons[method_key] = btn_frame
        
        # 更新滚动区域
        self.thumbnail_inner_frame.update_idletasks()
        self.thumbnail_canvas.config(scrollregion=self.thumbnail_canvas.bbox("all"))
        
        # 支持鼠标滚轮横向滚动
        def on_mousewheel(event):
            self.thumbnail_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
        
        self.thumbnail_canvas.bind("<Enter>", lambda e: self.thumbnail_canvas.bind_all("<MouseWheel>", on_mousewheel))
        self.thumbnail_canvas.bind("<Leave>", lambda e: self.thumbnail_canvas.unbind_all("<MouseWheel>"))
    
    def _create_thumbnail_button(self, parent: ttk.Frame, method_key: str, method_info: dict) -> ttk.Frame:
        """创建缩略图按钮"""
        btn_frame = ttk.Frame(parent, relief=tk.RAISED, borderwidth=2)
        btn_frame.method_key = method_key
        
        # 标题
        ttk.Label(
            btn_frame,
            text=method_info["name"],
            font=("Arial", 10, "bold")
        ).pack(pady=5)
        
        # 缩略图画布
        canvas = tk.Canvas(
            btn_frame,
            bg="#2b2b2b",
            highlightthickness=0,
            width=160,
            height=160
        )
        canvas.pack(pady=5, padx=5)
        btn_frame.canvas = canvas
        
        # 加载中提示
        loading_label = ttk.Label(
            canvas,
            text="生成中...",
            font=("Arial", 9),
            background="#2b2b2b",
            foreground="white"
        )
        canvas.create_window(90, 90, window=loading_label, tags="loading")
        btn_frame.loading_label = loading_label
        
        # 绑定点击事件
        def on_click(event=None):
            self.on_click(method_key)
        
        btn_frame.bind("<Button-1>", on_click)
        canvas.bind("<Button-1>", on_click)
        
        # 添加鼠标悬停效果
        def on_enter(event):
            btn_frame.config(relief=tk.SUNKEN, borderwidth=3)
        
        def on_leave(event):
            if self.selected_method != method_key:
                btn_frame.config(relief=tk.RAISED, borderwidth=2)
        
        btn_frame.bind("<Enter>", on_enter)
        btn_frame.bind("<Leave>", on_leave)
        canvas.bind("<Enter>", on_enter)
        canvas.bind("<Leave>", on_leave)
        
        return btn_frame
    
    def update_thumbnail(self, method_key: str, preview_image: np.ndarray):
        """更新缩略图"""
        if method_key not in self.thumbnail_buttons:
            return
        
        btn_frame = self.thumbnail_buttons[method_key]
        canvas = btn_frame.canvas
        
        # 移除加载提示
        canvas.delete("loading")
        if hasattr(btn_frame, 'loading_label'):
            btn_frame.loading_label.destroy()
        
        # 生成缩略图
        thumbnail_size = 150
        h, w = preview_image.shape[:2]
        scale = min(thumbnail_size / w, thumbnail_size / h)
        new_w = int(w * scale)
        new_h = int(h * scale)
        
        import cv2
        resized = cv2.resize(preview_image, (new_w, new_h))
        
        # 转换为PIL
        pil_image = Image.fromarray(resized)
        photo = ImageTk.PhotoImage(pil_image)
        
        # 居中显示
        x = (160 - new_w) // 2
        y = (160 - new_h) // 2
        
        canvas.create_image(x, y, anchor=tk.NW, image=photo)
        canvas.image = photo
    
    def select_method(self, method_key: str):
        """选中方法"""
        # 重置之前选中的
        if self.selected_method and self.selected_method in self.thumbnail_buttons:
            self.thumbnail_buttons[self.selected_method].config(relief=tk.RAISED, borderwidth=2)
        
        # 设置新选中
        self.selected_method = method_key
        if method_key in self.thumbnail_buttons:
            self.thumbnail_buttons[method_key].config(relief=tk.SUNKEN, borderwidth=3)

